﻿using System;
using System.Collections.Generic;
using System.Linq;
using _5E.Utils.CollectionHelper.GenericExtension;

namespace _5E.Utils.DbHelper.EasySQL.Creator
{
    /// <summary>
    /// 程序说明：创建查询SQL
    /// 创建作者：ahl5esoft
    /// 创建时间：2012-04-16
    /// </summary>
    class QueryCreator : BaseCreator, ICustomColumn, ICustomWhere
    {
        #region 变量

        private const string QUERY_SQL_FORMAT = "SELECT {0} FROM {1} {2}";

        private string[] m_Columns = null;

        private string m_Where = null;

        #endregion

        #region 构造函数

        public QueryCreator(string tableName, Dictionary<string, string> allColumns)
            : base(tableName, allColumns) { }

        #endregion

        #region 实例方法

        public ICustomColumn SetColumns(string[] propertyNames)
        {
            this.m_Columns = propertyNames;
            return this;
        }

        public ICustomWhere SetWhere(string where)
        {
            this.m_Where = ParseCondition.ToWhere(where, this.AllColumns);
            return this;
        }

        protected override string CreateSQL()
        {
            var columnString = this.GetColumnString();
            var sql = string.Format(QUERY_SQL_FORMAT, columnString, this.TableName, this.m_Where);
            return sql;
        }

        private string GetColumnString()
        {
            var filters = this.m_Columns.IsNullOrEmpty() ?
                this.AllColumns.Values.ToArray() : Array.ConvertAll(this.m_Columns, this.GetColumnName);
            var filterString = ToColumnString(filters);
            return filterString;
        }

        protected override void Reset()
        {
            this.m_Columns = null;
            this.m_Where = null;
        }

        #endregion
    }
}
